import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { ACCESS_TOKEN ,REFRESH_TOKEN } from '@/store/mutation-types'
import { MessageBox } from 'element-ui'

// import qs from 'qs'

//初始化axios
const http = axios.create({
	//请求失效时间
	timeout: 5000 ,
	//api 基础请求地址
	baseURL: process.env.baseURL
})

//请求拦截配置
http.interceptors.request.use(config =>{
	config.headers['version'] = "v1.0.0"
	config.headers['channelType'] = "eyeglass-web"
	if(store.getters.accessToken || Vue.ls.get(ACCESS_TOKEN)){
		config.headers['x-user-token'] = Vue.ls.get(ACCESS_TOKEN)
	}
	// 如果当前请求为刷新token配置刷新token请求头
	if(config.url == '/api/login/refreshToken'){
		if(store.getters.refreshToken || Vue.ls.get(REFRESH_TOKEN)){
			config.headers['x-refresh-token'] = Vue.ls.get(REFRESH_TOKEN)
		}
	}
	// if (config.url == '/api/upload/uploadImage') {
	// 	config.headers['Content-Type'] = 'multipart/form-data'
	// }
	if(config.url.match('/api/upload/u')){
		config.headers['Content-Type'] = 'multipart/form-data'
	}
	return config
})

//响应拦截配置
http.interceptors.response.use(
	response =>{
		//如果响应状态码为200,则说明接口请求成功，可以正常拿到数据
		if(response.data.responseCode === '200'){
			return Promise.resolve(response);
		}else {
			//如果返回结果为token失效则进行刷新token请求之后重新请求对象
			if(response.data.responseCode === '401001'){
				let config = response.config
				return store.dispatch('RefreshToken').then(() =>{
					config.headers['x-user-token'] = Vue.ls.get(ACCESS_TOKEN)
					return http(config)
				})
			}else if(response.data.responseCode === '401201' || response.data.responseCode === '401202'|| response.data.responseCode === '401002'){
				MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					store.dispatch('FrontEndLogout').then(() => {
						location.reload()// 为了重新实例化vue-router对象 避免bug
					})
				})
			}else {
				return Promise.reject(response); 
			}
		}
	},
	error =>{
		console.log('error',error)
	}
)

export default http